package com.promise.jokerdream.work.signin.lucky

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult
import java.time.LocalTime

// 幸运金蛋工作
class LuckyGoldenEggWork(override val uin: String): BaseWork(uin) {

    override val name: String
        get() = "幸运金蛋"

    override val priority: Int
        get() = 9

    override val isActWork: Boolean
        get() = true

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override suspend fun executeWork(): WorkResult {
        // 查询幸运金蛋信息
        val queryResult = gameApi.queryLuckyGoldenEgg()
        return queryResult.foldWithApiException(
            onSuccess = { response ->
                // 检查上午金蛋 (11:00-14:00)
                if (response.amStatus == 0 && isTimeInRange(11, 14)) {
                    val claimResult = gameApi.claimLuckyGoldenEgg(0)
                    claimResult.foldWithApiException(
                        onSuccess = { claimResponse ->
                            historyManager.addHistory(name, claimResponse.getDescription())
                        },
                        onFailure = { code, msg ->
                            historyManager.addHistory(name, msg, code)
                        }
                    )
                }
                
                // 检查下午金蛋 (19:00-22:00)
                if (response.pmStatus == 0 && isTimeInRange(19, 22)) {
                    val claimResult = gameApi.claimLuckyGoldenEgg(1)
                    claimResult.foldWithApiException(
                        onSuccess = { claimResponse ->
                            historyManager.addHistory(name, claimResponse.getDescription())
                        },
                        onFailure = { code, msg ->
                            historyManager.addHistory(name, msg, code)
                        }
                    )
                }
                
                WorkResult.Success
            },
            onFailure = { code, msg ->
                historyManager.addHistory(name, msg, code)
                WorkResult.Failure(Exception(msg), msg)
            }
        )
    }
    
    /**
     * 检查当前时间是否在指定时间范围内
     * @param startHour 开始小时
     * @param endHour 结束小时
     * @return 是否在时间范围内
     */
    private fun isTimeInRange(startHour: Int, endHour: Int): Boolean {
        val currentTime = LocalTime.now()
        val currentHour = currentTime.hour
        
        return currentHour in startHour until endHour
    }
}